package org.example.service.impl;

import org.example.entity.Permission;
import org.example.entity.Role;
import org.example.mapper.PermissionMapper;
import org.example.mapper.UserRoleMapper;
import org.example.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限服务实现类
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Override
    public List<String> getUserPermissions(Long userId) {
        try {
            // 从数据库查询用户权限
            List<String> permissions = permissionMapper.getPermissionsByUserId(userId);
            
            // 如果没有查询到权限，返回空列表
            if (permissions == null || permissions.isEmpty()) {
                return new ArrayList<>();
            }
            
            return permissions;
        } catch (Exception e) {
            // 记录错误日志，返回空权限列表
            // 这里可以添加日志记录
            return new ArrayList<>();
        }
    }
    
    @Override
    public Map<String, String> getPermissionMap() {
        try {
            // 默认返回平台端权限映射
            List<Permission> permissions = permissionMapper.getAllActivePermissionsByApp("platform");
            
            Map<String, String> permissionMap = new HashMap<>();
            
            if (permissions != null && !permissions.isEmpty()) {
                for (Permission permission : permissions) {
                    permissionMap.put(permission.getPermissionCode(), permission.getPermissionName());
                }
            }
            
            return permissionMap;
        } catch (Exception e) {
            // 记录错误日志，返回空映射
            // 这里可以添加日志记录
            return new HashMap<>();
        }
    }

    /**
     * 根据app返回对应权限映射
     */
    public Map<String, String> getPermissionMapByApp(String app) {
        try {
            List<Permission> permissions = permissionMapper.getAllActivePermissionsByApp(app);
            Map<String, String> permissionMap = new HashMap<>();
            if (permissions != null && !permissions.isEmpty()) {
                for (Permission permission : permissions) {
                    permissionMap.put(permission.getPermissionCode(), permission.getPermissionName());
                }
            }
            return permissionMap;
        } catch (Exception e) {
            return new HashMap<>();
        }
    }
    
    /**
     * 根据用户ID查询用户角色列表
     */
    public List<Role> getUserRoles(Long userId) {
        try {
            return userRoleMapper.getRolesByUserId(userId);
        } catch (Exception e) {
            // 记录错误日志，返回空列表
            return new ArrayList<>();
        }
    }
    
    /**
     * 根据用户ID查询用户主要角色
     */
    public Role getUserPrimaryRole(Long userId) {
        try {
            return userRoleMapper.getPrimaryRoleByUserId(userId);
        } catch (Exception e) {
            // 记录错误日志，返回null
            return null;
        }
    }
    
    /**
     * 检查用户是否有指定权限
     */
    public boolean hasPermission(Long userId, String permissionCode) {
        List<String> userPermissions = getUserPermissions(userId);
        return userPermissions.contains(permissionCode);
    }
    
    /**
     * 检查用户是否有指定权限列表中的任意一个
     */
    public boolean hasAnyPermission(Long userId, List<String> permissionCodes) {
        List<String> userPermissions = getUserPermissions(userId);
        return permissionCodes.stream().anyMatch(userPermissions::contains);
    }
    
    /**
     * 检查用户是否有指定权限列表中的所有权限
     */
    public boolean hasAllPermissions(Long userId, List<String> permissionCodes) {
        List<String> userPermissions = getUserPermissions(userId);
        return userPermissions.containsAll(permissionCodes);
    }
    
    // ========== 平台端专用方法 ==========
    
    /**
     * 根据用户ID查询平台端角色列表
     */
    public List<Role> getPlatformRolesByUserId(Long userId) {
        try {
            return userRoleMapper.getPlatformRolesByUserId(userId);
        } catch (Exception e) {
            // 记录错误日志，返回空列表
            return new ArrayList<>();
        }
    }
    
    /**
     * 根据用户ID查询平台端权限列表（仅以平台关联为准，不回退 primary_role_id）
     */
    public List<String> getPlatformPermissionsByUserId(Long userId) {
        try {
            List<String> platform = permissionMapper.getPlatformPermissionsByUserId(userId);
            return platform == null ? new ArrayList<>() : platform;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    /**
     * 根据角色ID查询权限列表
     */
    public List<String> getPermissionsByRoleId(Long roleId) {
        try {
            return permissionMapper.getPermissionsByRoleId(roleId);
        } catch (Exception e) {
            // 记录错误日志，返回空列表
            return new ArrayList<>();
        }
    }

    /**
     * 根据用户ID和公司ID查询企业端权限列表
     */
    public List<String> getEnterprisePermissionsByUserId(Long userId, Long companyId) {
        try {
            List<String> permissions = permissionMapper.getEnterprisePermissionsByUserId(userId, companyId);
            return permissions == null ? new ArrayList<>() : permissions;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    /**
     * 根据用户ID和公司ID查询用户端权限列表
     */
    public List<String> getUserPermissionsByUserId(Long userId, Long companyId) {
        try {
            List<String> permissions = permissionMapper.getUserPermissionsByUserId(userId, companyId);
            return permissions == null ? new ArrayList<>() : permissions;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
}



